const mdModel = require("../models/mdModel");

function changeGood(query) {
  return new Promise((resolve, reject) => {
    mdModel.findOne({ user_id: query.user_id }, (err, suc) => {
      err ? reject(err) : resolve(suc);
    });
  }).then(suc => {
    return new Promise((resolve, reject) => {
      let num = 0;
      for (let i = 0; i < suc.user_md.length; i++) {
        if (suc.user_md[i].title === query.title) {
          num = suc.user_md[i].good;
          break;
        }
      }
      num = num + 1;

      mdModel.findOneAndUpdate(
        {
          user_id: query.user_id,
          "user_md.title": query.title,
        },
        {
          $set: {
            "user_md.$.good": num,
          },
        },
        err => {
          err ? reject(err) : resolve();
        }
      );
    });
  });
}

function changeRead(query) {
  return new Promise((resolve, reject) => {
    mdModel.findOne({ user_id: query.user_id }, (err, suc) => {
      err ? reject(err) : resolve(suc);
    });
  }).then(suc => {
    return new Promise((resolve, reject) => {
      let num = 0;
      for (let i = 0; i < suc.user_md.length; i++) {
        if (suc.user_md[i].title === query.title) {
          num = suc.user_md[i].read;
          break;
        }
      }
      num = num + 1;

      mdModel.findOneAndUpdate(
        {
          user_id: query.user_id,
          "user_md.title": query.title,
        },
        {
          $set: {
            "user_md.$.read": num,
          },
        },
        err => {
          err ? reject(err) : resolve();
        }
      );
    });
  });
}

async function changeMd({ content, id, user_id, label, title }) {
  try {
    await mdModel.updateOne(
      {
        user_id,
      },
      {
        $set: {
          [`user_md.0.content`]: content,
          [`user_md.0.label`]: label,
          [`user_md.0.title`]: title,
        },
      }
    );
  } catch (err) {
    throw new Error(err);
  }
}

module.exports = {
  changeGood,
  changeRead,
  changeMd,
};
